Ext.define('CDR.view.ValidatorView' ,{
    extend: 'Ext.Component',
    alias: 'widget.checknameValidator',
    textValid: true,
    textError:'',
    initText: '',
    config: {
    	targetObject: null,
    	listenerObject: {
    		target: null,
    		event: ''
    	},
    	checkOn: null
    },
    initComponent: function() {
    	this.callParent();
    	var me = this;
    	if(this.targetObject) {
    		this.targetObject.on('blur', function(textfield, value){
    			var callServer = false;
    			var val = textfield.getValue();
    			if(val !== ''){
    				if(!me.initText) {
    					callServer = true;
    				} else if(me.initText !== val) {
    					callServer = true;
    				}
    			} 
    			if(callServer) {
    				//call ajax
					Ext.Ajax.request({
						method: 'GET',
						scope: me,
						async: false,
						url: 'checkname',
						params:{'name':val, checkOn: me.checkOn},
						success: function(response, opts) {
							var obj = Ext.decode(response.responseText);
							if(obj.success) {
								this.targetObject.clearInvalid();
								this.textValid = true;
							}else {
								this.textError = obj.msg;
								this.textValid = false;
							}
						},
						failure: function(response, opts) {
							var obj = Ext.decode(response.responseText);
							this.textError = obj.msg;
							this.textValid = false;
						}
					});	
	    			/*me.store.load({async: false, params:{'name':val, checkOn: me.checkOn}, callback: function(records, operation, success){
	    				if(success) {
	    					if(!records[0].data.isDuplicate) {
	    						me.targetObject.clearInvalid();
								me.textValid = true;
	    					} else {
	    						me.textError = records[0].data.msg;
								me.textValid = false;
	    					}
	    				} else {
	    					//console.log(operation)
	    					//console.log(records)
	    					me.textError = 'Has error when check name';
							me.textValid = false;
	    				}
		    			
	    			}});*/
	    			
	    			me.targetObject.validate();
	    			return;
    			}
    			
    			me.textValid = true;
				me.targetObject.clearInvalid();
				me.targetObject.validate();
    		});
    		this.targetObject.validator = function(){
    			return me.textValid ? me.textValid : me.textError;
    		}
    	}
    	if(this.listenerObject){
    		this.listenerObject.target.on(this.listenerObject.event, function(){
    			me.initText = me.targetObject.getValue();
    			me.textValid = true;
	    		me.textError = '';
	    		me.targetObject.clearInvalid();
    		});
    	}
    }
});